/**
 * File : ReactorManager.java <br/>
 * Author : alexgaoyh <br/>
 * Version : 1.1 <br/>
 * Date : 2017年7月5日 <br/>
 * Modify : <br/>
 * Package Name : com.MutiModule.common.codeing.reactor <br/>
 * Project Name : MutiModule-common <br/>
 * Description : <br/>
 * 
 */

package com.MutiModule.common.codeing.nio.reactor;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;

/**
 * ClassName : ReactorManager <br/>
 * Function : TODO ADD FUNCTION. <br/>
 * Reason : TODO ADD REASON. <br/>
 * Date : 2017年7月5日 下午1:35:10 <br/>
 * 
 * @author : alexgaoyh <br/>
 * @version : 1.1 <br/>
 * @since : JDK 1.6 <br/>
 * @see
 */

public class ReactorManager {

	private static final int SERVER_PORT = 7070;

	public void startReactor(int port) throws Exception {

		ServerSocketChannel server = ServerSocketChannel.open();
		server.socket().bind(new InetSocketAddress(port));
		server.configureBlocking(false);

		Reactor reactor = new Reactor();
		reactor.registerChannel(SelectionKey.OP_ACCEPT, server);

		reactor.registerEventHandler(SelectionKey.OP_ACCEPT, new AcceptEventHandler(reactor.getDemultiplexer()));

		reactor.registerEventHandler(SelectionKey.OP_READ, new ReadEventHandler(reactor.getDemultiplexer()));

		reactor.registerEventHandler(SelectionKey.OP_WRITE, new WriteEventHandler());

		reactor.run(); // Run the dispatcher loop

	}

	public static void main(String[] args) {
		System.out.println("Server Started at port : " + SERVER_PORT);
		try {
			new ReactorManager().startReactor(SERVER_PORT);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}
